package zzzhc.server;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.net.Socket;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.GetMethod;

public class RecognizeClient {
	private String host = "127.0.0.1";

	private int port = 5080;

	private Socket socket;

	private OutputStream out;

	private BufferedReader reader;

	public String getCode(byte[] imageData) throws IOException {
		if (socket == null) {
			socket = new Socket(host, port);
			out = socket.getOutputStream();
			reader = new BufferedReader(new InputStreamReader(socket
					.getInputStream()));
		}
		try {
			String s = imageData.length + "\r\n";
			out.write(s.getBytes());
			// out.flush();
			out.write(imageData);
			out.flush();
			String code = reader.readLine();
			return code;
		} catch (IOException e) {
			dispose();
			throw e;
		}
	}

	public void dispose() {
		if (socket != null) {
			try {
				socket.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
			socket = null;
		}
	}

	public String getCode(String url) throws Exception {
		HttpClient client = new HttpClient();
		GetMethod method = new GetMethod(url);
		try {
			client.executeMethod(method);
			return getCode(method.getResponseBody());
		} finally {
			method.releaseConnection();
		}
	}

	public static void main(String[] args) throws MalformedURLException,
			Exception {
		RecognizeClient client = new RecognizeClient();
		for (int i = 0; i < 3; i++) {
			String code = client
					.getCode("http://blog.sina.com.cn/myblog/checkwd_image.php?1162179879921");
			System.out.println(code);
		}
		client.dispose();
	}

}
